<template>
  <div class="app-container" style="display: flex;box-sizing: border-box;">
    <div v-loading="loading"
      style="width: 315px;height: 100% !;max-height: 100%;margin-right: 20px;padding: 20px;border-right: 1px solid #f2f2f2;">
      <div style="margin-bottom: 10px;border-bottom: 1px solid #f2f2f2;padding-bottom: 10px;">
        分类列表
      </div>
      <div style="display: flex;align-items: center;cursor: pointer; margin-bottom: 10px;">
        <el-radio-group v-model="current" @change="handleTabsClick">
          <el-radio-button v-for="(item,index) in data_read" :key="item.value"
            :label="item.value">{{item.label}}</el-radio-button>
        </el-radio-group>
      </div>
      <div style="height: 1000px;overflow-y: auto;">
        <div @click="handleDataTypeItemClick(item)"
          :class="['dataTypeItem', queryParams.classificationId == item.classificationId ? 'active' : '']"
          v-for="(item,index) in dataTypeList" :key="item.classificationId">
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <div style="margin-right: 20px;">
              <span>{{item.classificationName}}</span>
              <span :style="{color: item.count == item.cacheCount ? '#409EFF' : '#f56c6c'}">（{{item.count ==
                item.cacheCount ? item.count :item.cacheCount ? item.cacheCount : 0 + '/' + item.count}}）</span>
            </div>
            <dict-tag :options="data_share" :value="item.classificationType" />
          </div>
        </div>
        <el-empty v-if="dataTypeList.length == 0" description="暂无数据" />
      </div>
    </div>
    <div style="width: 70%;flex: 1;">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户" prop="userId" v-if="checkRole(['admin'])">
          <el-select v-model="queryParams.userId" placeholder="" clearable>
            <el-option v-for="(item,index) in userList" :key="item.userId" :label="item.userName"
              :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <!-- :disabled="selection.length > 0 ? false : true" -->
          <el-button type="primary" v-hasPermi="['dataList:dataList:batch']" @click="batchTransfer" plain
            icon="Edit">批量转移</el-button>
        </el-col>
        <el-col :span="1.5">
          <!-- :disabled="selection.length > 0 ? false : true" -->
          <el-button  v-hasPermi="['dataList:dataList:filter']" type="primary" @click="handleSettingFilter" plain icon="Setting">设置筛选</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            v-hasPermi="['dataList:dataList:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['dataList:dataList:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['dataList:dataList:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['dataList:dataList:export']">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
        </el-col>
        <el-col :span="1.5" v-hasPermi="['dataList:dataList:clear']">
          <el-dropdown  split-button type="primary" @click="removeAllData(2)">
            清空当前分类数据
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item  @click="removeAllData(0)">清除当前选择分类未读所有数据</el-dropdown-item>
                <el-dropdown-item  @click="removeAllData(1)">清除当前选择分类已读所有数据</el-dropdown-item>
                <el-dropdown-item @click="handleRemoveFilterDataList()">清除当前分类筛选数据</el-dropdown-item>
              </el-dropdown-menu>
            </template>
            </el-dropdown>
          <!-- <el-button type="info" v-hasPermi="['dataList:dataList:clear']" plain icon="FolderDelete"
            @click="removeAllData">清空当前分类数据</el-button> -->
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <div>
        <Table ref="pageTableRef" :table-data="tableData" :border="true" size="small" :loading="loading"
          :columns="columns" :is-pagination="true" :selection="true" :show-index="true" :total="total" tableHeight="800"
          :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" @changeSize="handleSizeChange"
          @changeCurrent="handleCurrentChange" @handleSelectionChange="handleSelectionChange" :is-click="true">
          <!-- <template #dataId="scope">
            <span @click="handleCopy(scope.row.dataId)"
              style="color: #409eff;cursor: pointer;">{{scope.row.dataId}}</span>
          </template> -->
          <template #status="scope">
            <div>
              <dict-tag :options="data_read" :value="scope.row.status" />
            </div>
          </template>
          <template #cacheType="scope">
            <div>
              <dict-tag :options="cache_type" :value="scope.row.cacheType" />
            </div>
          </template>
          <template #action="scope">
            <div>
              <el-button size="small" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['dataList:dataList:edit']">修改</el-button>
              <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['dataList:dataList:remove']">删除</el-button>
            </div>
          </template>
        </Table>
      </div>
    </div>

    <!-- 添加或修改数据列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px">
      <el-form ref="dataListRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="分类" prop="classificationName">
          <el-input v-model="form.classificationName" placeholder="请输入分类id" />
        </el-form-item> -->
        <!-- v-if="checkRole(['dataList:dataList:user'])" -->
        <el-form-item label="用户" prop="userId" v-if="checkRole(['admin'])">
          <el-select v-model="form.userId" placeholder="" clearable style="width: 100%;">
            <el-option v-for="(item,index) in userList" :key="item.userId" :label="item.userName"
              :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in data_read" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-for="(item,index) in form.dataJsonArray" :key="index">
          <!-- :prop="item.dataName" -->
          <el-form-item v-if="item.dataType == 1" :label="item.dataValue">
            <el-input v-model="item.formValue" @input="dataJsonInputChange($event,form.dataJsonArray,item)"
              :placeholder="'请输入'+ item.dataValue" />
          </el-form-item>
        </div>
        <!-- <el-form-item label="" prop="data2">
          <el-input v-model="form.data2" placeholder="请输入" />
          ...
        <el-form-item label="" prop="data30">
          <el-input v-model="form.data30" placeholder="请输入" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="uploadLoding" @click="submitFileForm">确 定</el-button>
          <el-button :disabled="uploadLoding" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="批量转移" v-model="transferShow" @close="transferCancel" width="40%">
      <div>
        <el-form :model="batchParams" :rules="batchRules" ref="transferRef" :inline="true" label-width="100px">
          <el-form-item label="是否已读：" required prop="status">
            <el-select v-model="batchParams.status" :disabled="batchLoading" clearable placeholder="请选择是否共享">
              <el-option v-for="dict in data_read" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目标分类：" required prop="classificationId">
            <el-select v-model="batchParams.classificationId" :disabled="batchLoading" clearable placeholder="请选择是否共享">
              <el-option v-for="(item,index) in dataTypeList" :key="item.classificationId"
                :label="item.classificationName" :value="item.classificationId">
                <template #default>
                  <div style="display: flex;align-items: center;justify-content: space-between;">
                    <div style="margin-right: 20px;">
                      <span>{{item.classificationName}}</span>
                      <span style="color: #409EFF;">（{{item.count}}）</span>
                    </div>
                    <dict-tag :options="data_share" :value="item.classificationType" />
                  </div>
                </template>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="转移条件：" required prop="status">
            <el-select v-model="batchParams.sourceStatus" :disabled="batchLoading" clearable placeholder="请选择转移条件">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="dict in data_read" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <div v-if="transferTableData.length > 0">
          <Table :table-data="transferTableData" :border="true" size="small" :loading="batchLoading"
            :columns="transferTableColumns" :is-pagination="false" :selection="false" :show-index="true">
            <template #status="scope">
              <div>
                <dict-tag :options="data_read" :value="scope.row.status" />
              </div>
            </template>
            <template #cacheType="scope">
              <div>
                <dict-tag :options="cache_type" :value="scope.row.cacheType" />
              </div>
            </template>
            <template #action="scope">
              <div>
                <el-button size="small" link type="primary" icon="Delete"
                  @click="handleTransferDelete(index)">移除</el-button>
              </div>
            </template>
          </Table>
        </div>
        <div v-else style="margin-left: 20px;font-size: 16px;">
          由<span style="padding: 0 10px;color: #409EFF;">{{queryParams.classificationName}}（{{current == '0' ? '未读' :
            '已读'}}）</span> 全部转移到 <span style="padding: 0 10px;color: #409EFF;">{{dataTypeList.find((item) => {return
            batchParams.classificationId
            == item.classificationId}) ? dataTypeList.find((item) => {return batchParams.classificationId ==
            item.classificationId}).classificationName: ''}}（{{batchParams.status == '0' ? '未读' : '已读' }}）</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="batchLoading" @click="transferSubmit">确 定</el-button>
          <el-button :disabled="batchLoading" @click="transferCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="筛选" v-model="showFilter" @close="filterCancel" width="45%">
      <el-form ref="filterData" :model="filterForm" :rules="filterRules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-row :gutter="24" v-for="(items,indexs) in filterForm.filterDataList" :key="indexs">
              <el-col :span="3">
                <div style="width: 100%;display: flex;justify-content: flex-end;">
                  <el-button @click="addFilter" type="primary" icon="Plus" circle
                    v-if="indexs === filterForm.filterDataList.length - 1" />
                  <el-button @click="delFilter(indexs)" type="danger" icon="Delete" circle
                    v-if="filterForm.filterDataList.length > 1" />
                </div>
              </el-col>
              <el-col :span="6">
                <el-form-item label="字段：" :rules="filterRules.field" required
                  :prop="'filterDataList.' + indexs + '.field'">
                  <el-select :disabled="filterLoading" v-model="items.field" clearable placeholder="请选择字段">
                    <el-option v-for="(item,index) in data_list_columns" :key="index" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="" label-width="0" required :rules="filterRules.fieldType"
                  :prop="'filterDataList.' + indexs + '.fieldType'">
                  <el-select :disabled="filterLoading" v-model="items.fieldType" clearable placeholder="条件">
                    <el-option v-for="(item,index) in rule_type" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="" label-width="0" required :rules="filterRules.filterData1"
                  :prop="'filterDataList.' + indexs + '.filterData1'">
                  <el-input :disabled="filterLoading" v-model="items.filterData1" placeholder="请输入内容" />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="['介于', '不介于'].includes(items.fieldType)">
                <el-form-item label="" label-width="0" required :rules="filterRules.filterData2"
                  :prop="'filterDataList.' + indexs + '.filterData2'">
                  <el-input :disabled="filterLoading" v-model="items.filterData2" placeholder="请输入内容" />
                </el-form-item>
              </el-col>

            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" plain :disabled="filterLoading" @click="filterSubmit('1')">重置筛选</el-button>
          <el-button type="primary" :disabled="filterLoading" @click="filterSubmit">确 定</el-button>
          <el-button :disabled="filterLoading" @click="filterCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DataList">
  import { getToken } from "@/utils/auth";
  import { listDataList, getDataList, delDataList, addDataList, updateDataList, dataListClassification, dataBatchPaste, removeAllDataListByDataClassification, getSettingFilter, setSettingFilter, removeFilterDataList } from "@/api/dataList/dataList";
  import { listUser } from "@/api/system/user";
  import { checkPermi, checkRole } from "@/utils/permission";
  import pinyin from 'js-pinyin';
  // checkPermi 是否有权限
  // checkRole 是否管理员 v-if="checkRole(['admin'])"
  const { proxy } = getCurrentInstance();
  const { data_read } = proxy.useDict('data_read');
  const { data_share } = proxy.useDict('data_share');
  const { cache_type } = proxy.useDict('cache_type');
  const { rule_type } = proxy.useDict('rule_type');
  const { data_list_columns } = proxy.useDict('data_list_columns');
  // console.log(data_read.value, 'ABCDEFG-data_read')
  const dataListList = ref([]);
  const open = ref(false);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const userList = ref([]);
  const dataTypeList = ref([]);
  // const dataTypeItemId = ref('')
  const current = ref(0); // 0 已读，1未读
  const selection = ref([]);
  const transferShow = ref(false);
  const showFilter = ref(false);
  const transferTableColumns = ref([]);
  const transferTableData = ref([]);
  const tableData = ref([]);
  const columns = ref([]);
  const TableLoading = ref(false);
  const pageTableRef = ref(null);
  const listJsonArray = ref([]);
  const batchLoading = ref(false);
  const filterLoading = ref(false);
  const selectClassificationId = ref();
  const selectClassificationName = ref();
  const uploadLoding = ref(false);
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 100,
      classificationId: '',
      classificationName: undefined,
      userId: undefined,
      status: '0',
      pid: undefined,
      createBy: undefined,
      createTime: undefined,
      updateBy: undefined,
      updateTime: undefined,
      // dataJsonArray: []
      // data1: undefined,
      // ...
      // data30: undefined
    },
    rules: {
      userId: [
        { required: true, message: "请选择用户", trigger: "blur" }
      ],
      status: [
        { required: true, message: "请选择状态", trigger: "change" }
      ],
      data1: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data2: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data3: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data4: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data5: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data6: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data7: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data8: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data9: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data10: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data11: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data12: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data13: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data14: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data15: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data16: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data17: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data18: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data19: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data20: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data21: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data22: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data23: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data24: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data25: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data26: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data27: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data28: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data29: [
        { required: true, message: "请输入值", trigger: "blur" }
      ],
      data30: [
        { required: true, message: "请输入值", trigger: "blur" }
      ]
    },
    batchRules: {
      classificationId: [
        { required: true, message: "请选择目标分类", trigger: "change" }
      ],
      status: [
        { required: true, message: "请选择状态", trigger: "change" }
      ],
    },
    batchParams: {
      dataIds: '', // 数据主键id
      classificationId: '', // 分类状态
      status: '', // 已读未读状态
      sourceStatus: '',
    },
    filterForm: {
      filterDataList: []
    },
    filterRules: {
      field: [
        { required: true, message: "请选择字段", trigger: "change" }
      ],
      fieldType: [
        { required: true, message: "请选择条件", trigger: "change" }
      ],
      filterData1: [
        { required: true, message: "请输入值1", trigger: "blur" }
      ],
      filterData2: [
        { required: true, message: "请输入值2", trigger: "blur" }
      ],
    }
  });
  const { queryParams, form, rules, batchParams, batchRules, filterForm, filterRules } = toRefs(data);
  // 点击复制
  const handleCopy = (row) => {
    proxy.clickCopyFun(row);
  };
  /*** 用户导入参数 */
  const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/dataList/dataList/importData"
  });
  const filterCancel = () => {
    showFilter.value = false;
    filterLoading.value = false;
    filterForm.value.filterDataList = [];
  };
  const handleSettingFilter = () => {
    getSettingFilter({ classificationId: queryParams.value.classificationId,  }).then(response => {
      // console.log(response, 'ABCDEFG-getSettingFilter');
      // let list = response.rows || [];
      if (response.data) {
        filterForm.value.filterDataList = JSON.parse(response.data);
      } else {
        filterForm.value.filterDataList.push(
          {
            field: '',
            fieldType: '',
            filterData1: '',
            filterData2: '',
          }
        );
      }
      filterLoading.value = true;
      setTimeout(() => {
        showFilter.value = true;
        filterLoading.value = false;
      }, 500);
    });
  };
  const addFilter = () => {
    filterForm.value.filterDataList.push(
      {
        field: '',
        fieldType: '',
        filterData1: '',
        filterData2: '',
      }
    );
  };
  const delFilter = (index) => {
    filterForm.value.filterDataList.splice(index, 1);
  };
  const filterSubmit = (type) => {
    proxy.$refs["filterData"].validate(valid => {
      if (valid) {
        filterLoading.value = true;
        let json = type == '1' ? null : JSON.stringify(filterForm.value.filterDataList)
        let params = {
          json: json,
          classificationId: queryParams.value.classificationId,
          // status: queryParams.value.status
          // userId: 1
        };
        filterLoading.value = true;
        setSettingFilter(params).then(response => {
          // console.log(response, 'ABCDEFG-dataBatchPaste')
          proxy.$modal.msgSuccess("设置成功");
          setTimeout(() => {
            dataListTypeList();
            filterLoading.value = false;
            showFilter.value = false;
          }, 500);
        }).catch(() => {
          filterLoading.value = false;
        });
      } else {
        filterLoading.value = false;
      }
    });
  };
  const batchTransfer = () => {
    // let List = dataTypeList.value
    // let selectItemId = queryParams.value.classificationId
    // console.log(List, 'ABCDEFG-List');
    // console.log(selectItemId, 'ABCDEFG-selectItemId');
    // if(List.length > 0) {
    //   List.forEach((item) =>{
    //     item.disabled = false
    //     if(item.classificationId == selectItemId) {
    //       item.disabled = true
    //     }
    //   })
    // }
    transferTableColumns.value = columns.value;
    transferTableData.value = selection.value;
    transferShow.value = true;
  };
  const handleTransferDelete = (index) => {
    transferTableData.value.splice(index, 1);
  };
  /** 导入按钮操作 */
  function handleImport() {
    upload.title = "用户导入";
    upload.open = true;
  };
  /** 下载模板操作 */
  function importTemplate() {
    proxy.download("dataList/dataList/importTemplate", {
    }, `user_template_${new Date().getTime()}.xlsx`);
  };
  /**文件上传中处理 */
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
  };
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    uploadLoding.value = false;
    dataListTypeList();
    getList();
  };
  /** 提交上传文件 */
  function submitFileForm() {
    uploadLoding.value = true;
    proxy.$refs["uploadRef"].submit();
  };


  /** 查询数据列表列表 */
  function getList() {
    loading.value = true;
    listDataList(queryParams.value).then(response => {
      // console.log(response, 'ABCDEFG-listDataList')
      let list = response.rows || [];
      // if (list && list.length > 0) {
      //   list.forEach((item, index) => {
      //     item.tableColumns = JSON.parse(JSON.stringify(JSON.parse(item.tableHead)))
      //     item.columns = []
      //     if (item.tableColumns && item.tableColumns.length > 0) {
      //       item.tableColumns.forEach((items, indexs) => {
      //         if (items.dataType == '1') {
      //           item.columns.push({
      //             prop: items.dataName,
      //             label: items.dataValue,
      //             // slot: '',
      //             minWidth: 150,
      //             align: 'center',
      //             showOverflowTooltip: true,
      //           })
      //         }
      //       })

      //     }
      //     // console.log(item, 'tableColumns')
      //   })
      // }

      // columns.value = list && list.length > 0 ? [...list[0].columns, ...defaultColumns] : [...defaultColumns]
      tableData.value = list;
      // console.log(tableData.value, 'tableData');
      total.value = response.total;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    });
  }
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  // 批量转移 取消
  function transferCancel() {
    selection.value = [];
    transferTableColumns.value = [];
    transferTableData.value = [];
    transferShow.value = false;
    pageTableRef.value.clearTableSelection();
    batchParams.value.dataIds = '';
    batchParams.value.classificationId = '';
    batchParams.value.status = '';
    batchLoading.value = false;
    proxy.resetForm("transferRef");
    // console.log(selection.value, 'transferTable')
    // getList()
  }
  // 批量转移
  const transferSubmit = () => {
    let params = {
      // dataIds: '', // 数据主键id
      // classificationId: '',  // 分类id
      // status: '' // 已读未读状态
      beforeClassificationId: queryParams.value.classificationId,
      ...batchParams.value
    };
    params.dataIds = transferTableData.value.length > 0 ? transferTableData.value.map((item) => { return item.dataId; }) ? transferTableData.value.map((item) => { return item.dataId; }) : [] : [];
    // console.log(queryParams.value, 'ABCDEFG-queryParams')
    // console.log(params, 'ABCDEFG-setDataBatchPasteApi')
    // return
    proxy.$refs["transferRef"].validate(valid => {
      if (valid) {
        batchLoading.value = true;
        dataBatchPaste(params).then(response => {
          // console.log(response, 'ABCDEFG-dataBatchPaste')
          transferCancel();
          dataListTypeList();
        }).catch(() => {
          batchLoading.value = false;
        });
      } else {
        batchLoading.value = false;
      }
    });

  };
  // 表单重置
  function reset() {
    form.value = {
      dataId: null,
      classificationId: selectClassificationId.value,
      userId: null,
      status: '0',
      // pid: null,
      // createBy: null,
      // createTime: null,
      // updateBy: null,
      // updateTime: null,
      dataJsonArray: []
      // data1: null,
      // ...
      // data30: null
    };
    proxy.resetForm("dataListRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    dataListTypeList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }


  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    title.value = "添加数据列表";
    form.value.dataJsonArray = listJsonArray.value;
    form.value.classificationId = queryParams.value.classificationId;
    open.value = true;
    // console.log(form.value, 'ABCDEFG-add')
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    loading.value = true;
    reset();
    const _dataId = row.dataId || ids.value;
    getDataList(_dataId).then(response => {
      // console.log(response, 'ABCDEFG-edit');
      loading.value = false;
      form.value = response.data;
      // 解析 tableHead JSON 字符串
      const tableHeadData = response.data.tableHead ? JSON.parse(response.data.tableHead) : [];
      if (tableHeadData.length > 0) {
        // 更新 newTableHead 对象
        tableHeadData.forEach(item => {
          const dataName = item.dataName;
          if (response.data.hasOwnProperty(dataName)) {
            item.formValue = response.data[dataName];
          }
        });
      }
      // console.log(tableHeadData,'ABCDEFG-tableHeadData');
      form.value.dataJsonArray = tableHeadData.length > 0 ? tableHeadData : [];
      open.value = true;
      title.value = "修改数据列表";
    });
  }
  const dataJsonInputChange = (val, list, row) => {
    // console.log(val, 'dataJsonInputChange-val');
    // console.log(list, 'dataJsonInputChange-list');
    // console.log(row, 'dataJsonInputChange-row');

    list.forEach(item => {
      const dataName = item.dataName;
      if (row.dataName == dataName) {
        // if (form.value.hasOwnProperty(dataName)) {
        form.value[dataName] = item.formValue;
        // }
      }
    });
    // console.log(form.value, 'dataJsonInputChange-form');
    // let
  };
  /** 提交按钮 */
  function submitForm() {
    // console.log(form.value, 'ABCDEFG-submitForm');
    // let isNull = form.value.dataJsonArray.every(item => item.formValue)
    // console.log(isNull, 'ABCDEFG-isNull');
    // if (isNull == false) {
    //   proxy.$modal.msgError(`暂无开启的参数数据，请到分类管理开启!`)
    //   return
    // }
    // return
    proxy.$refs["dataListRef"].validate(valid => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.dataId != null) {
          updateDataList(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            dataListTypeList();
            reset();
            // getList()
          }).finally(() => {
            buttonLoading.value = false;
          });
        } else {
          addDataList(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            // getList()
            dataListTypeList();
            reset();
          }).finally(() => {
            buttonLoading.value = false;
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _dataIds = row.dataId || ids.value;
    proxy.$modal.confirm('是否确认删除数据列表编号为"' + _dataIds + '"的数据项？').then(function () {
      loading.value = true;
      return delDataList(_dataIds);
    }).then(() => {
      loading.value = true;
      dataListTypeList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    }).finally(() => {
      loading.value = false;
    });
  }
  // 清空当前分类数据
  const removeAllData = (type) => {
    // selectClassificationId.value
    const _dataIds = selectClassificationId.value;
    let mesArr = ['分类下未读所有数据', '分类下已读所有数据', '分类下的所有数据？','当前配置筛选的数据']
    let text = mesArr[type] // type 0 未读 1已读 2全部
    proxy.$modal.confirm('是否确认删除 "' + selectClassificationName.value + '" ' + text).then(function () {
      loading.value = true;
      return removeAllDataListByDataClassification(_dataIds, type);
    }).then(() => {
      loading.value = true;
      dataListTypeList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    }).finally(() => {
      setTimeout(() => {
        loading.value = false;
      }, 1000);
    });
  };
  // 筛选数据删除
  const handleRemoveFilterDataList = () => {
      // selectClassificationId.value
      const _dataIds = selectClassificationId.value;
      proxy.$modal.confirm('是否确认删除 "' + '当前配置筛选的数据" ').then(function () {
        loading.value = true;
        return removeFilterDataList(_dataIds);
      }).then(() => {
        loading.value = true;
        dataListTypeList();
        proxy.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        setTimeout(() => {
          loading.value = false;
        }, 1000);
      });
    };
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('dataList/dataList/export', {
      ...queryParams.value
    }, `dataList_${new Date().getTime()}.xlsx`);
  }
  /** 查询用户列表 */
  function getListUser() {
    listUser().then(res => {
      // console.log(res, 'ABCDEFG-getListUser');
      // loading.value = false;
      userList.value = res.rows;
      // total.value = res.total;
    });
  };
  // 点击已读未读
  function handleTabsClick(index) {
    current.value = index;
    queryParams.value.status = index;
    dataListTypeList();
  }
  // function customSort(a, b) {
  //   function getFirstLetter(name) {
  //     const pinyin = PinyinHelper.convertToPinyin(name, '', true, true)
  //     return pinyin.toLowerCase().charCodeAt(0)
  //   }

  //   const firstLetterA = getFirstLetter(a.classificationName)
  //   const firstLetterB = getFirstLetter(b.classificationName)

  //   if (firstLetterA === firstLetterB) {
  //     return a.classificationName.localeCompare(b.classificationName)
  //   } else {
  //     return firstLetterA - firstLetterB
  //   }
  // }
  // 分类
  function dataListTypeList() {
    // dataListClassification
    let params = {
      status: current.value
    };
    dataListClassification(params).then(res => {
      // console.log(res, 'ABCDEFG-dataListTypeList');
      // console.log(, '123');
      let list = res.data;
      // 获取数据列表通过对classificationName字段，设置排序根据字母排序，同时相同字母的再按长短排序
      if (list.length > 0) {
        list.forEach((item) => {
          item.pinyin = pinyin.getFullChars(item.classificationName);
        });

        list.sort((a, b) => {
          // First, sort alphabetically
          if (a.pinyin[0] < b.pinyin[0]) return -1;
          if (a.pinyin[0] > b.pinyin[0]) return 1;

          // if (a.pinyin < b.pinyin) return -1
          // if (a.pinyin > b.pinyin) return 1

          // If names are the same, sort by length
          return a.classificationName.length - b.classificationName.length;
        });
        // console.log(list, 'ABCDEFG-list');
      }
      dataTypeList.value = list || [];
      // console.log(list)
      listJsonArray.value = res.data.length > 0 && selectClassificationId.value ? res.data.find((item) => { return item.classificationId == selectClassificationId.value; }) ? JSON.parse(res.data.find((item) => { return item.classificationId == selectClassificationId.value; }).tableHead) : [] : res.data.length > 0 && res.data[0].tableHead ? JSON.parse(res.data[0].tableHead) : [];
      // console.log(selectClassificationId.value, 'queryParams.value')
      let newColumns = getTableHeadJsonArray(res.data.find((item) => { return item.classificationId == selectClassificationId.value; }));
      columns.value = newColumns;
      // console.log(listJsonArray.value, 'listJsonArray.value')0
      let rowId = selectClassificationId.value ? selectClassificationId.value : list.length > 0 ? list[0].classificationId : '';
      let rowName = selectClassificationName.value ? selectClassificationName.value : list.length > 0 ? list[0].classificationName : '';
      selectClassificationId.value = rowId;
      selectClassificationName.value = rowName;
      batchParams.value.classificationId = rowId;
      // const current = ref(0); // 0 已读，1未读
      batchParams.value.status = current.value == '0' ? '1' : '0';
      queryParams.value.classificationId = rowId;
      queryParams.value.classificationName = rowName;
      if (res.data.length > 0) {
        getList();
      } else {
        loading.value = false;
      }
    });
  }
  const getTableHeadJsonArray = (row) => {
    let tableHead = row && row.tableHead ? JSON.parse(row.tableHead) : [];
    let newColumns = [];
    if (tableHead.length > 0) {
      tableHead.forEach((item) => {
        // console.log(item, 'tableHead')
        if (item.dataType == '1') {
          newColumns.push({
            prop: item.dataName,
            label: item.dataValue ? item.dataValue + '（' + item.dataName + '）' : item.dataName,
            // slot: '',
            isClick: true,
            minWidth: 200,
            align: 'center',
            showOverflowTooltip: true,
          });
        }
      });
    }
    let defaultColumns = [
      {
        prop: 'classificationName',
        label: '分类名称',
        slot: '',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属用户',
        slot: '',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'status',
        label: '状态',
        slot: 'status',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'cacheType',
        label: '缓存状态',
        slot: 'cacheType',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'createBy',
        label: '创建者',
        slot: '',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'createTime',
        label: '创建时间',
        slot: '',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'updateBy',
        label: '更新者',
        slot: '',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'updateTime',
        label: '更新时间',
        slot: '',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        fixed: 'right',
        slot: 'action',
        label: '操作',
        minWidth: 150,
        align: 'center'
      }
    ];
    let lastColumn = row ? [...newColumns, ...defaultColumns] : defaultColumns;
    lastColumn.unshift({
      prop: 'dataId',
      label: 'ID',
      // slot: '',
      minWidth: 150,
      // slot: 'dataId',
      isClick: true,
      align: 'center',
      showOverflowTooltip: true,
    });
    return lastColumn;
  };
  function handleDataTypeItemClick(row) {
    queryParams.value.classificationId = row.classificationId;
    queryParams.value.classificationName = row.classificationName;
    selectClassificationId.value = row.classificationId;
    selectClassificationName.value = row.classificationName;
    batchParams.value.classificationId = row.classificationId;
    batchParams.value.status = current.value == '0' ? '1' : '0';
    let tableHead = row.tableHead ? JSON.parse(row.tableHead) : [];
    listJsonArray.value = tableHead;
    // console.log(row.tableHead, 'row.tableHead')
    let newColumns = getTableHeadJsonArray(row);
    // console.log(newColumns, '[...columns, ...defaultColumns]');
    columns.value = newColumns;
    getList();
  }
  const handleSizeChange = (val) => {
    queryParams.value.pageSize = val;
    getList();
  };
  const handleCurrentChange = (val) => {
    // console.log(val,'ABCDEFG-handleCurrentChange');
    queryParams.value.pageNum = val;
    // console.log(queryParams.value, 'ABCDEFG-queryParams.value');
    getList();
  };
  // // 多选框选中数据
  // function handleSelectionChange(selection) {
  //   ids.value = selection.map(item => item.dataId)
  //   single.value = selection.length != 1
  //   multiple.value = !selection.length
  // }
  const handleSelectionChange = (val) => {
    selection.value = val;
    ids.value = val.map(item => item.dataId);
    single.value = val.length != 1;
    multiple.value = !val.length;
    // console.log(selection.value, 'ABCDEFG-handleSelectionChange')
  };
  // getList()
  // console.log(checkRole(['admin']), '1111222');
  if (checkRole(['admin'])) {
    getListUser();
  }
  dataListTypeList()
</script>
<style lang="scss" scoped>
  .dataTypeItem {
    padding: 6px 10px;
    cursor: pointer;
    border-bottom: 1px solid #f2f2f2;
  }

  .active {
    background: rgba(66, 161, 255, .3);
    /* color: #fff; */
  }

  .dataTypeItem:hover {
    background: rgba(66, 161, 255, .3);
    /* color: #fff; */
  }

  .el-row {
    display: flex;
    /* align-items: center; */
    flex-wrap: wrap;
  }

  .demo-ruleForm {
    width: 100%;

    :deep() {
      .el-input:not(.el-message-box__input .el-input) {
        max-width: 100% !important;
      }

      .el-select {
        width: 100% !important;
      }

      .el-input {
        width: 100% !important;
      }

      .el-date-editor--daterange.el-input,
      .el-date-editor--daterange.el-input__inner,
      .el-date-editor--timerange.el-input,
      .el-date-editor--timerange.el-input__inner {
        width: 100% !important;
        flex: 1 !important;
      }
    }
  }

  :deep() {
    .el-dialog {
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -40%);
      max-height: calc(100% - 60px);
      max-width: calc(100% - 30px);
    }

    .el-dialog .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  }
</style>
